package cn.sciento.starter.keyencrypt.json;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import java.util.Iterator;
import cn.sciento.starter.keyencrypt.core.Encrypt;
import cn.sciento.starter.keyencrypt.core.IEncryptionService;

public class EncryptedDeserializerModifier extends BeanDeserializerModifier {
  private final IEncryptionService encryptionService;
  
  public EncryptedDeserializerModifier(IEncryptionService encryptionService) {
    this.encryptionService = encryptionService;
  }
  
  public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, BeanDescription beanDescription, BeanDeserializerBuilder builder) {
    Iterator<SettableBeanProperty> it = builder.getProperties();
    while (it.hasNext()) {
      SettableBeanProperty p = it.next();
      Encrypt encrypt = p.getAnnotation(Encrypt.class);
      if (null != encrypt) {
        JsonDeserializer<Object> current = p.getValueDeserializer();
        builder.addOrReplaceProperty(p.withValueDeserializer(new EncryptedJsonDeserializer(this.encryptionService, current, p, encrypt)), true);
      } 
    } 
    return builder;
  }
}
